<template>
    <div>
        <!--添加按钮和模态框-->
        <a-button type="primary" @click="showModal('add')">
            添加
        </a-button>
        <!--对话框-->
        <a-modal
                :visible="visible"
                :title= "modelTitle"
                :confirm-loading="confirmLoading"
                okText='确认'
                cancel-text="取消"
                @cancel="hideModel"
                @ok="submit"
        >
            <!--表单-->
            <a-form-model :model="form">
                <a-form-model-item label="登录用户名">
                    <a-input :disabled="form.username_disable" v-model="form.username" />
                </a-form-model-item>
                <a-form-model-item label="密码">
                    <a-input type="password" v-model="form.password" placeholder="为空保持原密码"/>
                </a-form-model-item>
                <a-form-model-item label="角色">
                    <!--
                        选择框
                        mode 模式
                        value 默认选中值
                    -->
                    <a-select
                            mode="multiple"
                            :value="form.role"
                            style="width: 100%"
                            :showArrow="true"
                            :filterOption="selectInput"
                            placeholder="请选择角色"
                            @change="changeRole"
                    >
                        <a-select-option v-for="(value, key) in role" :key="value.id">
                            {{ value.title }}
                        </a-select-option>
                    </a-select>
                </a-form-model-item>
                <a-form-model-item label="状态">
                    <a-radio-group v-model="form.status">
                        <a-radio value="1">
                            启用
                        </a-radio>
                        <a-radio value="0">
                            禁用
                        </a-radio>
                    </a-radio-group>
                </a-form-model-item>
            </a-form-model>
        </a-modal>

        <!--表格-->
        <!--
            :columns="columns"  表头数据
            :data-source="data" 表格数据
            rowKey="id"   id为 data 中的一个属性
            :loading="loading" 表格是否load
            :pagination="pagination" 分页参数
        -->
        <a-table :columns="columns" :data-source="data" rowKey="id" :loading="loading" :pagination="pagination"  >

            <span slot="status" slot-scope="text, record, index" v-if="record.id !== 1">
                <div v-if="text === 1">
                    <a-button type="primary" @click="changeActive(text, record, index)">已启用</a-button>
                </div>
                <div v-else>
                    <a-button type="danger" @click="changeActive(text, record, index)">已禁用</a-button>
                </div>
            </span>
            <!--插槽一定要在表格组件标签中-->
            <!--定义插槽渲染-->
            <!--
                slot="action" 表示是在columns（某列）中的表头值为action中插入标签，往这个位置插入插槽span中间的内容
                slot-scope="text, record, index"
                    text    表示当前行当前列的值
                    record  表示当前行的数据
                    index   表格索引
            -->
            <span slot="action" slot-scope="text, record, index">
                <div v-if="record.id === 1">
                    <span>超级用户不能编辑</span>
                </div>
                <div v-else>
                    <a-button type="primary" @click="edit(text, record, index)">编辑</a-button>
                    <!--气泡确认框-->
                    <a-popconfirm
                        title="是否删除?"
                        @confirm="() => del(text, record, index)"
                    >
                        <a-button type="danger">
                            删除
                        </a-button>
                    </a-popconfirm>
                </div>

            </span>

            <template slot="operation" slot-scope="text, record">
                <a-popconfirm
                        v-if="dataSource.length"
                        title="Sure to delete?"
                        @confirm="() => onDelete(record.key)"
                >
                    <a href="javascript:;">Delete</a>
                </a-popconfirm>
            </template>
        </a-table>

    </div>
</template>
<script>
    export default {
        // 在实例中使用 components 属性注册需要用到的组件
        //注册组件
        data() {
            return {
                //表格数据
                data : [],
                /**
                 * 表头数据
                 * title 为表头的标题
                 * dataIndex为列数据在数据项中对应的 key
                 * scopedSlots 对应插槽
                 */
                columns : [
                    {
                        title: '登录用户名',
                        dataIndex: 'username',
                    },
                    {
                        title: '状态',
                        dataIndex: 'status',
                        scopedSlots: {customRender: 'status'},
                    },
                    {
                        title: '操作',
                        dataIndex: 'action',
                        //使用插槽
                        scopedSlots: {customRender: 'action'},
                    },
                ],
                //所有角色
                role : [],
                //表格load标志
                loading : true,
                //表格分页参数
                pagination: {
                    //pageNo: 2,
                    current: 1,
                    pageSize: 10, // 默认每页显示数量
                    showSizeChanger: true, // 显示可改变每页数量
                    pageSizeOptions: ['10', '20', '50', '100'], // 每页数量选项
                    showTotal: total => `共 ${total} 条数据`, // 显示总数
                    onShowSizeChange: (current, pageSize) => this.changePageSize(current, pageSize), // 改变每页数量时更新显示
                    onChange:(current,pageSize)=>this.changePage(current,pageSize),//点击页码事件
                    total:0 //总条数
                },
                //模态对话框标题
                modelTitle: '',
                //模态框是否显示
                visible: false,
                //表单load
                confirmLoading: false,

                //from 初始化
                form : {
                    id : 0,
                    username : '',
                    password : '',
                    status : '1',
                    role : [],

                    //操作类型
                    operation_type : 'add',
                    //username input 禁用状态
                    username_disable : false,

                }
            };
        },
        //页面渲染之前,$el创建之后 去加载
        mounted() {
            //获取列表
            this.getList();
            this.getRoleList();
        },
        methods: {
            //获取列表
            getList(param) {
                //初始化分页参数
                if(param === undefined || param === null){
                    param = {
                        current : 1,
                        pageSize : 10
                    }
                }

                this.axios.get(process.env.VUE_APP_API_URL + this.urls.admin_list,{params: {
                    pageNow : param.current,
                    pageSize : param.pageSize,
                }}).then((data) => {
                    //修改loading 状态
                    this.loading = false;
                    //数据
                    this.data = data.data.data.data;
                    //分页参数
                    //更新数据总条数
                    this.pagination.total = data.data.data.lineCount;
                });
            },
            //获取角色列表并设置
            getRoleList(){
                this.axios.get(process.env.VUE_APP_API_URL + this.urls.role_list).then((data) => {

                    var data = data.data.data.data;

                    var role = [];
                    //移除超级管理员
                    for(let key in data){
                        if(data[key].id === 1){
                            continue;
                        }
                        role.push(data[key]);
                    }
                    //数据
                    this.role = role;
                });
            },

            //点击页码事件
            changePage(current,pageSize) {
                /*console.log(page, '当前页.......');
                console.log(pageSize, '每页大小.......');*/
                this.pagination.current = current;
                this.pagination.pageSize = pageSize;
                this.getList({
                    current : current,
                    pageSize : pageSize
                })
            },

            //每页显示数量改变的事件
            changePageSize(current, pageSize){
                /*console.log(current, '当前页.......');
                console.log(pageSize, '每页大小.......');*/
                this.pagination.current = current;
                this.pagination.pageSize = pageSize;
                this.getList({
                    current : current,
                    pageSize : pageSize
                })
            },
            //角色选择框选择改变事件
            changeRole(value) {
                //console.log(value);
                this.form.role = value;
            },
            //下拉选择，输入过滤
            selectInput(inputValue, option){
                //console.log(inputValue, option,111111)
                return (
                    option.componentOptions.children[0].text.toLowerCase().indexOf(inputValue.toLowerCase()) >= 0
                );
            },
            //显示模态对话框
            showModal(type) {
                //console.log(type, 'type........');
                //设置对话框标题
                type === 'add'? this.modelTitle = '添加':this.modelTitle = '编辑'
                this.visible = true;
            },
            //关闭模态框
            hideModel() {
                this.visible = false;
                this.resetForm();
            },

            //重置form状态
            resetForm(){
                this.form = {
                    id : 0,
                    username : '',
                    nickname : '',
                    password : '',
                    status : '1',
                    role : [],

                    //操作类型
                    operation_type : 'add',
                    //username input 禁用状态
                    username_disable : false,
                }
            },

            //确认提交
            submit(){
                //基准地址
                var url = process.env.VUE_APP_API_URL;
                //接口路由
                if(this.form.operation_type === 'add'){
                    this.pagination.current = 1;
                    url += this.urls.admin_add;
                }
                if(this.form.operation_type === 'edit'){
                    url += this.urls.admin_edit;
                }
                if(this.form.operation_type === 'del'){
                    url += this.urls.admin_del;
                }
                if(this.form.operation_type === 'change_status'){
                    url += this.urls.admin_change_status;
                }
                //发送请求
                this.axios.post(url, this.form).then((data) => {

                    //错误提示
                    /*if(data.data.code !== 200){
                        this.$message.error(data.data.msg);
                        return;
                    }*/

                    //重新刷新表格
                    this.data = this.getList()
                    //恢复默认
                    this.resetForm();
                    //关闭按钮的load状态
                    this.confirmLoading = false;
                    //关闭模态框
                    this.visible = false;

                    //改变页码
                    if(this.form.operation_type === 'add'){
                        this.pagination.current = 1;
                    }
                });
            },
            //编辑
            edit(text, record, index) {
                //console.log(record);
                //设置模态框的form表单的值和选中
                this.form.id = record.id;
                this.form.username = record.username;
                this.form.nickname = record.nickname;
                //this.form.password = record.password;
                this.form.status = ''+record.status;

                console.log(this.form.role, 'role........');

                //角色选择框的选中
                var tempRole = [];
                for(var i = 0; i < record.roles.length; i++){
                    tempRole.push(record.roles[i].id);
                }
                this.form.role = tempRole;

                console.log(this.form.role, 'role........');

                //切换用户名input 状态,改为禁用
                this.form.username_disable = true;
                //切换操作类型
                this.form.operation_type = 'edit';

                //显示模态框
                this.showModal();
            },

            //编辑
            del(text, record, index) {
                //console.log('删除.........');
                this.form.id = record.id;
                //切换操作类型
                this.form.operation_type = 'del';
                //提交
                this.submit();
            },

            //改变状态
            changeActive(text, record, index) {
                //console.log(record)
                this.form.id = record.id;
                //切换操作类型
                this.form.operation_type = 'change_status';
                //提交
                this.submit();
            },

        },
    };
</script>
